package ups.glre.news.struts.action;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;

import ups.glre.news.model.User;
import ups.glre.news.service.CategoryService;
import ups.glre.news.service.UserService;
import ups.glre.news.struts.form.LoginForm;

public class LoginAction extends Action {
	
	private UserService userService;
	
	private CategoryService categoryService;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)  {
		
		ActionMessages errors = form.validate(mapping, request);		
		ActionForward resultat; 
		
		// Get login and password
		String login = ((LoginForm) form).getLogin();
		String password = ((LoginForm) form).getPassword();
		
	    // EJB doesn't seems to work with struts 1
		InitialContext ic = null;
		try {
			ic = new InitialContext();
			userService = (UserService) ic.lookup("glre-news/UserServiceImpl/local");
			categoryService = (CategoryService) ic.lookup("glre-news/CategoryServiceImpl/local");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Only for testing	
		userService.populateUserTables();
		categoryService.populateCategoryTables();
		
		// Authenticate from DB 
		if (userService.authenticate(login, password)){	
			User user = userService.getUserByLogin(login);
			/*
			request.setAttribute("login", user.getLogin()); 
			request.setAttribute("userId", user.getUserId());
			*/
			request.getSession().setAttribute("user", user);
			resultat = (mapping.findForward("succes"));
		}else{
			errors.add("authentication", new ActionError("error.authentication"));
			this.saveErrors(request, errors);
			resultat = (mapping.findForward("echec"));
		}
		
		return resultat;
	}	

}
